package com.kangzhili.nettypush.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.kangzhili.nettypush.enums.MessageCode;
import com.kangzhili.nettypush.dto.RequestBody;
import com.kangzhili.nettypush.dto.ResponseBody;

/**
 * WebSocket消息帧处理器
 * 处理客户端发来的WebSocket消息，并可实现消息广播、点对点推送等功能
 */
public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketFrameHandler.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 客户端连接建立时，添加到Channel管理器
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        WebSocketChannelManager.add(ctx.channel());
        logger.info("客户端连接：{} 已加入", ctx.channel().id().asShortText());
    }

    /**
     * 客户端断开连接时，从Channel管理器移除
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        WebSocketChannelManager.remove(ctx.channel());
        logger.info("客户端连接：{} 已移除", ctx.channel().id().asShortText());
    }

    /**
     * 处理接收到的WebSocket消息帧
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
        if (frame instanceof TextWebSocketFrame) {
            String requestText = ((TextWebSocketFrame) frame).text();
            logger.info("收到客户端消息: {}", requestText);
            try {
                // 反序列化为RequestMessage
                RequestBody<Object> reqMsg = objectMapper.readValue(requestText, objectMapper.getTypeFactory().constructParametricType(RequestBody.class, Object.class));
                MessageCode msgCode = MessageCode.fromCode(reqMsg.getCode());
                ResponseBody<Object> respMsg;
                switch (msgCode) {
                    case BIND:
                        // 绑定用户ID到Channel
                        WebSocketChannelManager.bindUser(reqMsg.getUserId(), ctx.channel());
                        respMsg = new ResponseBody<>(0, reqMsg.getUserId(), "用户绑定成功");
                        ctx.channel().writeAndFlush(new TextWebSocketFrame(objectMapper.writeValueAsString(respMsg)));
                        break;
                    case BROADCAST:
                        // 广播消息
                        WebSocketChannelManager.broadcast(new TextWebSocketFrame(objectMapper.writeValueAsString(
                                new ResponseBody<>(0, reqMsg.getUserId(), reqMsg.getData())
                        )));
                        break;
                    case HEARTBEAT:
                        // 心跳响应
                        respMsg = new ResponseBody<>(0, reqMsg.getUserId(), "pong");
                        ctx.channel().writeAndFlush(new TextWebSocketFrame(objectMapper.writeValueAsString(respMsg)));
                        break;
                    default:
                        // 未知code
                        respMsg = new ResponseBody<>(-1, reqMsg.getUserId(), "不支持的操作类型: " + reqMsg.getCode());
                        ctx.channel().writeAndFlush(new TextWebSocketFrame(objectMapper.writeValueAsString(respMsg)));
                }
            } catch (Exception e) {
                logger.error("消息解析或处理异常", e);
                ResponseBody<Object> errorMsg = new ResponseBody<>(-1, null, "消息格式错误或处理异常");
                try {
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(objectMapper.writeValueAsString(errorMsg)));
                } catch (Exception ignored) {}
            }
        } else if (frame instanceof CloseWebSocketFrame) {
            ctx.close();
        } else {
            logger.warn("不支持的WebSocket帧类型: {}", frame.getClass().getName());
        }
    }

    /**
     * 处理异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("WebSocket处理异常", cause);
        ctx.close();
    }
} 